<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <template v-if="formType === 'query'">
      <!-- 基本信息 -->
      <!-- <div style="padding: 20px 10px 0 10px;">
        <div style="font-weight: bold; font-size: 16px; margin-bottom: 10px;">基本信息</div>
        <el-row :gutter="24">
          <el-col :span="8">物料号：{{ formData.itemCode }}</el-col>
          <el-col :span="8">物料名称：{{ formData.itemName }}</el-col>
          <el-col :span="8">物料类型：{{ formData.materialType === '0' ? '半成品' : formData.materialType === '1' ? '成品' : '' }}</el-col>
        </el-row>
        <el-row :gutter="24" style="margin-top: 8px;">
          <el-col :span="8">物料单位：{{ formData.unit }}</el-col>
          <el-col :span="8">物料图号：{{ formData.drawingNo }}</el-col>
          <el-col :span="8">物料描述：{{ formData.itemDesc }}</el-col>
        </el-row>
        <el-row :gutter="24" style="margin-top: 8px;">
          <el-col :span="8">物料规格：{{ formData.itemSpecification }}</el-col>
          <el-col :span="8">物料品牌：{{ formData.brand }}</el-col>
          <el-col :span="8">数量：{{ formData.qty }}</el-col>
        </el-row>
        <el-row :gutter="24" style="margin-top: 8px;">
          <el-col :span="8">主图：<span v-if="formData.mainImage"><a :href="formData.mainImage" target="_blank">查看图片</a></span></el-col>
        </el-row>
      </div> -->
      <div class="basic-info">
        <h3 class="info-title">基本信息</h3>
        <div class="info-grid">
          <div class="info-row">
            <span class="info-label">物料号：</span>
            <span class="info-content">{{ formData.itemCode }}</span>
          </div>
          <div class="info-row">
            <span class="info-label">物料名称：</span>
            <span class="info-content">{{ formData.itemName }}</span>
          </div>
          <div class="info-row">
            <span class="info-label">物料类型：</span>
            <span class="info-content">{{
                getMaterialLabel(formData.materialType)
            }}</span>
          </div>
        </div>

        <div class="info-grid">
          <div class="info-row">
            <span class="info-label">物料单位：</span>
            <span class="info-content">{{ formData.unit }}</span>
          </div>
          <div class="info-row">
            <span class="info-label">物料图号：</span>
            <span class="info-content">{{ formData.drawingNo }}</span>
          </div>
          <div class="info-row">
            <span class="info-label">材料描述：</span>
            <span class="info-content">{{ formData.itemDesc }}</span>
          </div>
        </div>

        <div class="info-grid">
          <div class="info-row">
            <span class="info-label">物料规格：</span>
            <el-tooltip
              class="item"
              effect="dark"
              :content="formData.itemSpecification"
              placement="top-start"
            >
              <span class="info-content">{{ formData.itemSpecification }}</span>
            </el-tooltip>
          </div>
          <div class="info-row">
            <span class="info-label">物料品牌：</span>
            <span class="info-content">
              {{ formData.brand?formData.brand:'--' }}
            </span>
          </div>
          <div class="info-row">
            <span class="info-label">数量：</span>
            <span class="info-content">{{ formData.qty }}</span>
          </div>
        </div>
        <div class="info-grid">
          <div class="info-row">
            <span class="info-label">主图：</span>
            <span class="info-content"
              ><span v-if="formData.mainImage"
                ><a :href="formData.mainImage" target="_blank">查看图片</a></span
              ></span
            >
          </div>
        </div>
      </div>
      <!-- 出入库记录 -->
      <div style="margin-top: 30px; padding: 0 10px;">
        <div style="font-weight: bold; font-size: 16px; margin-bottom: 10px;">出入库记录</div>
        <el-table :data="formData.materialStocks || []" border stripe style="width: 100%;">
          <el-table-column label="序列号" prop="serialNo" width="230" />
          <el-table-column label="位置" prop="location" />
          <el-table-column label="批次号" prop="batchNo" />
          <el-table-column label="出入库类型" prop="stockType" >
            <template #default="scope">
                <span>{{ scope.row.stockType === '1' ? '入库' : scope.row.stockType === '2' ? '出库' : '' }}</span>
            </template>
           </el-table-column>
          <el-table-column label="来源" prop="dataSource" />
          <el-table-column label="数量" prop="qty">
            <template #default="scope">
              <span :style="scope.row?.type === '出库' ? 'font-weight:bold;color:#000;' : ''">{{ scope.row?.qty }}</span>
            </template>
          </el-table-column>
          <el-table-column label="日期" prop="createTime" :formatter="dateFormatter"/>
<!--          <el-table-column label="人员" prop="creator" />-->
        </el-table>
      </div>
    </template>
    <template v-else>
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"

        v-loading="formLoading"
        :disabled="formType === 'query'"
      >
        <el-form-item label="序列号" prop="serialNo">
          <el-input v-model="formData.serialNo" placeholder="请输入序列号" />
        </el-form-item>
        <el-form-item label="批次号" prop="batchNo">
          <el-input v-model="formData.batchNo" placeholder="请输入批次号" />
        </el-form-item>
        <el-form-item label="工单号" prop="docNo">
          <el-input v-model="formData.docNo" placeholder="请输入工单号" />
        </el-form-item>
        <el-form-item label="材料品号" prop="itemCode">
          <el-input v-model="formData.itemCode" placeholder="请输入材料品号" />
        </el-form-item>
        <el-form-item label="材料品名" prop="itemName">
          <el-input v-model="formData.itemName" placeholder="请输入材料品名" />
        </el-form-item>
        <el-form-item label="材料规格" prop="itemSpecification">
          <el-input v-model="formData.itemSpecification" placeholder="请输入材料规格" />
        </el-form-item>
        <el-form-item label="材料描述" prop="itemDesc">
          <el-input v-model="formData.itemDesc" placeholder="请输入材料描述" />
        </el-form-item>
        <el-form-item label="材料图号" prop="drawingNo">
          <el-input v-model="formData.drawingNo" placeholder="请输入材料图号" />
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="formData.unit" placeholder="请输入单位" />
        </el-form-item>
        <el-form-item label="物料类型" prop="materialType">
          <el-select v-model="formData.materialType" placeholder="请选择物料类型">
            <el-option label="请选择字典生成" value="" />
          </el-select>
        </el-form-item>
        <el-form-item label="品牌" prop="brand">
          <el-input v-model="formData.brand" placeholder="请输入品牌" />
        </el-form-item>
        <el-form-item label="数量" prop="qty">
          <el-input v-model="formData.qty" placeholder="请输入数量" />
        </el-form-item>
        <el-form-item label="主图" prop="mainImage">
          <UploadImg v-model="formData.mainImage" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio value="1">请选择字典生成</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <!-- 子表的表单 -->
      <el-tabs v-model="subTabsName" v-if="formType !== 'query'">
        <el-tab-pane label="物料出入库记录" name="materialStock">
          <MaterialStockForm ref="materialStockFormRef" :serial-no="formData.id" />
        </el-tab-pane>
      </el-tabs>
    </template>
    <template #footer>
      <el-button v-if="formType === 'query'" @click="dialogVisible = false">关闭</el-button>
      <template v-else>
        <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </template>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { MaterialInventorApi, MaterialInventorVO } from '@/api/opticore/materialinventor'
import MaterialStockForm from './components/MaterialStockForm.vue'
import { dateFormatter } from '@/utils/formatTime'
import {getStrDictOptions} from "@/utils/dict";

/** 中间库 表单 */
defineOptions({ name: 'MaterialInventorForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改；query - 查看
const formData = ref({
  id: undefined,
  serialNo: undefined,
  batchNo: undefined,
  docNo: undefined,
  itemCode: undefined,
  itemName: undefined,
  itemSpecification: undefined,
  itemDesc: undefined,
  drawingNo: undefined,
  unit: undefined,
  materialType: undefined,
  brand: undefined,
  qty: undefined,
  mainImage: undefined,
  status: undefined,
  materialStocks: [] // 添加 materialStocks 属性
})
const formRules = reactive({
})
const formRef = ref() // 表单 Ref

/** 子表的表单 */
const subTabsName = ref('materialStock')
const materialStockFormRef = ref()

/** 打开弹窗 */
const open = async (type: string, row?: any) => {
  dialogVisible.value = true
  // dialogTitle.value = t('action.' + type)
  dialogTitle.value = "查看"
  formType.value = type
  resetForm()
  // 修改时，设置数据
  console.log(row,"-------------");
  if (row) {
    formLoading.value = true

    try {
    //   // 获取基本信息
    //   const data = await MaterialInventorApi.getMaterialInventor(row.id)
    //   formData.value = data
      formData.value=row;
      console.log("打印传递过来的数据行",formData.value);
    //   // 如果是查看模式，获取出入库记录
      if (type === 'query') {
        console.log('获取出入库记录行，id:', row.id) // 添加日志
        console.log('获取出入库记录行，serialNo:', row.serialNo) // 添加日志
        //传入物料 +类型 查询 所有的序列号
        //row.itemSpecification    Cable,GJ,8F,3.0mm,OM4,C,Micro,PVC(OFNR),Aqua[PS-009(Pantone 325C)]
        // 对参数进行 URL 编码
        const encodedItemSpecification = encodeURIComponent(row.itemSpecification);
        const stockList = await MaterialInventorApi.getMaterialStockListBySerialNos(row.itemCode,encodedItemSpecification)
        console.log('出入库记录:', stockList) // 添加日志
        formData.value.materialStocks = stockList
      }
    } catch (error) {
      console.error('获取数据失败:', error) // 添加错误日志
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

// 获取接口数据
const materialTypes = computed(() => {
  return getStrDictOptions(DICT_TYPE.OPTICORE_MATE_TYPE);
});

const getMaterialLabel = (materialType) => {
  const material = materialTypes.value.find(item => item.value === materialType);
  return material ? material.label : '';
};

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  if (formType.value === 'query') return
  // 校验表单
  await formRef.value.validate()
  // 校验子表单
  try {
    await materialStockFormRef.value.validate()
  } catch (e) {
    subTabsName.value = 'materialStock'
    return
  }
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as MaterialInventorVO
    // 拼接子表的数据
    data.materialStocks = materialStockFormRef.value.getData()
    if (formType.value === 'create') {
      await MaterialInventorApi.createMaterialInventor(data)
      message.success(t('common.createSuccess'))
    } else {
      await MaterialInventorApi.updateMaterialInventor(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    serialNo: undefined,
    batchNo: undefined,
    docNo: undefined,
    itemCode: undefined,
    itemName: undefined,
    itemSpecification: undefined,
    itemDesc: undefined,
    drawingNo: undefined,
    unit: undefined,
    materialType: undefined,
    brand: undefined,
    qty: undefined,
    mainImage: undefined,
    status: undefined,
    materialStocks: [] // 添加 materialStocks 属性
  }
  formRef.value?.resetFields()
}
</script>
<style scope>
.basic-info {
  font-family: Arial, sans-serif;
  padding: 20px;
  /* background-color: #f9f9f9; */
  border-radius: 8px;
}

.info-title {
  font-size: 18px;
  margin-bottom: 20px;
  color: #333;
}

.info-grid {
  display: flex;
  /* justify-content: space-between; */
  margin-bottom: 15px;
  border-bottom: 1px solid #eee;
  padding-bottom: 15px;
}

.info-row {
  /* flex: 1; */
  width: 33.3%;
  display: flex;
  margin-right: 10px;
}

.info-label {
  font-weight: bold;
  color: #666;
  min-width: 100px;
}

.info-content {
  color: #333;

  white-space: nowrap; /* 防止文字换行 */
  overflow: hidden; /* 文字溢出隐藏 */
  text-overflow: ellipsis; /* 出现省略号 */
}

.view-link {
  color: #1890ff;
  text-decoration: none;
  margin-left: 5px;
  cursor: pointer;
}

.other-info {
  margin-top: 15px;

}

.other-info .info-content {
  word-break: break-word;
}
</style>
